<template>
  <div class="verification-container">
    <div
      v-for="(code, index) in verificationCodes"
      :key="index"
      :class="`verification-input ${focusedIndex === index ? 'focused' : ''}`"
      @click="handleFocus(index)"
    >
      {{ verificationCodes[index] }}
      <div v-if="focusedIndex === index && verificationCodes[index] === ''" class="cursor"></div>
    </div>
    <wd-keyboard
      :hideOnClickOutside="false"
      v-model:visible="hsaFocused"
      @input="onInput"
      @delete="onDelete"
    ></wd-keyboard>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
const verificationCodes = ref(['', '', '', '', '', ''])
const focusedIndex = ref(0)
const hsaFocused = ref(false)

onMounted(() => {
  setTimeout(() => {
    focusedIndex.value = 0
    hsaFocused.value = true
  }, 500)
})

const handleFocus = (index) => {
  focusedIndex.value = index
  hsaFocused.value = true
}

const emit = defineEmits(['input'])
const onInput = (value) => {
  if (focusedIndex.value >= 0) {
    verificationCodes.value[focusedIndex.value] = value
    if (focusedIndex.value < verificationCodes.value.length - 1) {
      focusedIndex.value += 1
    } else {
      hsaFocused.value = false
    }
    emit('input', verificationCodes.value.join(''))
  }
}

const onDelete = () => {
  if (focusedIndex.value >= 0) {
    if (verificationCodes.value[focusedIndex.value] === '') {
      if (focusedIndex.value > 0) {
        focusedIndex.value -= 1
      }
    } else {
      verificationCodes.value[focusedIndex.value] = ''
    }
    emit('input', verificationCodes.value.join(''))
  }
}

defineExpose({
  clean: () => {
    verificationCodes.value = ['', '', '', '', '', '']
    focusedIndex.value = 0
  },
})
</script>

<style lang="scss" scoped>
@keyframes blink {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

.verification-container {
  display: flex;
}

.verification-input {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 96rpx;
  height: 96rpx;
  margin-right: 20rpx;
  font-size: 40rpx;
  text-align: center;
  background: #f4f6f8;
  border: 1rpx solid #ccc;
  border-radius: 16rpx;
}

.verification-input.focused {
  color: #1db157;
  border-color: #1db157;
  box-shadow: 0 0 4rpx #1db157;
}

.cursor {
  position: absolute;
  width: 2rpx;
  height: 50%;
  background: #1db157;
  animation: blink 1s infinite;
}
</style>
